package com.sau.pixelcart.common.utils;

import com.sau.pixelcart.common.properties.EmailProperties;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Properties;

public class MailUtil {

    public static boolean sendMail(EmailProperties emailProperties, String to, String title, String content) {
        try {
            Properties properties = new Properties();
            properties.put("mail.smtp.host",  emailProperties.getHost());
            properties.put("mail.smtp.auth",  emailProperties.isAuth());
            properties.put("mail.user",  emailProperties.getUser());
            properties.put("mail.password",  emailProperties.getCode());

            // 核心修正点
            properties.put("mail.smtp.ssl.enable",  "true");
            properties.put("mail.smtp.port",  "465");
            properties.put("mail.smtp.ssl.protocols",  "TLSv1.2");
            properties.put("mail.debug",  "true");

            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(emailProperties.getUser(),  emailProperties.getCode());
                }
            };

            Session session = Session.getInstance(properties,  authenticator);
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new  InternetAddress(emailProperties.getUser()));
            message.setRecipient(Message.RecipientType.TO,  new InternetAddress(to));
            message.setSubject(title);
            message.setContent(content,  "text/html;charset=UTF-8");

            Transport.send(message);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}